package io.hellsinger.vortex.ui.screen.storage.media

import android.graphics.BitmapFactory
import io.hellsinger.viewmodel.BitViewModel
import io.hellsinger.viewmodel.intent
import io.hellsinger.vortex.Dispatchers
import io.hellsinger.vortex.data.model.PathItem
import io.hellsinger.vortex.domain.repository.StorageRepository
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runInterruptible

class StorageMediaViewModel(
    private val dispatchers: Dispatchers,
    private val repository: StorageRepository,
) : BitViewModel<UiState>(scopeName = "Storage Media scope") {
    private val state: MutableUiState = MutableUiState()

    override fun getUiState(): UiState = state

    fun load(item: PathItem) =
        intent {
            if (state.image != null) return@intent
            val loading =
                launch {
                    delay(1000L)
                    update(UPDATE_LOADING_EVENT)
                }

            val result =
                runInterruptible(dispatchers.io) {
                    BitmapFactory.decodeFile(item.path.toString())
                }

            state.image = result

            loading.cancel()
            update(UPDATE_IMAGE_LOADED_EVENT)
        }

    companion object {
        const val UPDATE_IMAGE_LOADED_EVENT = 1 shl 0
        const val UPDATE_LOADING_EVENT = 1 shl 1
    }
}
